package se.teamscape.client.presenter;

import java.util.ArrayList;
import java.util.List;

import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.place.PlaceRequest;
import net.customware.gwt.presenter.client.place.TokenFormatter;
import se.teamscape.client.place.ShowPersonPlace;
import se.teamscape.client.rpc.CachingDispatchAsync;
import se.teamscape.client.rpc.DispatchCallback;
import se.teamscape.shared.model.Model;
import se.teamscape.shared.model.TeamPlayer;
import se.teamscape.shared.rpc.DBQuery;
import se.teamscape.shared.rpc.ModelsQuery;
import se.teamscape.shared.rpc.ModelsQueryResult;

import com.google.inject.Inject;

/**
 * Presenter to list team players.
 * 
 * @author Andreas Borglin
 * 
 */
public class ListPlayersPresenter extends ListModelsPresenter {

    private final CachingDispatchAsync mDispatcher;
    private final TokenFormatter mFormatter;

    @Inject
    public ListPlayersPresenter(Display display, EventBus eventBus, CachingDispatchAsync dispatcher, TokenFormatter formatter) {
        super(display, eventBus);
        this.mDispatcher = dispatcher;
        this.mFormatter = formatter;
    }

    @Override
    protected void onLazyBind() {

    }

    private void updateData() {

        DBQuery query = DBQuery.selectFrom(TeamPlayer.class.getName()).where(TeamPlayer.TEAMKEY_FIELD, Model.KEY_TYPE,
                DBQuery.EQUALS, getId());

        mDispatcher.executeWithCache(new ModelsQuery(query), new DispatchCallback<ModelsQueryResult>() {

            @Override
            public void callback(ModelsQueryResult result) {
                List<Model> models = result.getModels();
                List<String> places = new ArrayList<String>();
                for (Model model : models) {
                    TeamPlayer player = (TeamPlayer) model;
                    PlaceRequest req = new PlaceRequest(ShowPersonPlace.NAME).with(ShowPersonPlace.PARAM_ID, player
                            .getPersonKey());
                    places.add(mFormatter.toHistoryToken(req));
                }

                display.setData(models, places);
                viewUpdated();
            }
        });

    }

    @Override
    protected void onRevealDisplay() {

        if (needsUpdate()) {
            updateData();
        }
    }
}
